var express = require('express');
var router = express.Router();
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/douban";
var async = require('async');


router.get('/', function(req, res, next) {
  res.render('comment', {});
}); 


router.get('/list',function(req,res,next){

  console.log('list-----------------------')

  // 分页码，每页显示记录数，总记录数，总页码
  var pageNo = req.query.pageNo,
  pageNo = pageNo?pageNo:1,
  pageSize = 5,
  count = 0,
  totalPages = 0;

  var findData = function(db,callback){
    // 连接表
    var conn = db.collection('comment');
    // var data = {title:req.query.title}
    // console.log(data);
    // 并行无关联
    async.parallel([
      function(callback){
        conn.find({}).toArray(function(err,results){
          if(err){
            return;
          }else{
            totalPages = Math.ceil(results.length/pageSize);
            count = results.length;
            callback(null,results);
          }
        })
      },
      function(callback){
        conn.find({}).sort({_id:-1}).skip( (pageNo-1)*pageSize).limit(pageSize).toArray(function(err,results){
          if(err){
            return;
          }else{
            callback(null,results);
          }
        })
      }
    ],function(err,results){
      callback(results[1]);
    })

  }

   MongoClient.connect(DB_CONN_STR,function(err,db){
      if(err){
        console.log(err)
        return;
      }else{
        findData(db,function(results){
          res.render('list',{
            pageNo:pageNo,
            totalPages:totalPages,
            list: results,
            count:count
          })
        })

        db.close();
      }
    })
})




module.exports = router;
